/**
 * 更改菜品
 */

//引入Q模块
var Q = require('q');
//引入公共函数
var util = require('../../util');
//引入fileSystem模块
var fs = require('fs');

//add入口函数
var index = function(getData, postData, config, _redis, db) {
	let deferred = Q.defer();
	util.isSet(postData.foodId, postData.foodType, postData.foodName, postData.foodPrice).then(function() {
		//console.log('老图片名：' + postData.oldFileName);

		var updateData = {
			foodType: postData.foodType,
			foodName: postData.foodName,
			foodPrice: postData.foodPrice, 
			foodTimestamp: parseInt(Date.now() / 1000)
		};

		if(postData.fileName) {
			updateData.foodPhoto = postData.fileName;
		}

		
		//更新菜品
		db.update('foodMenu', {
			foodId: postData.foodId	
		}, updateData).then(function(){
			console.log(updateData);
			deferred.resolve(1);
			if(postData.oldFileName && postData.foodPhotoFolder && postData.fileName) {
				util.fsExists(foodPhotoPath).then(function() {
					foodPhotoPath = config.uploadPath + '/' + postData.storeId + '/' + postData.foodPhotoFolder + '/' + postData.oldFileName;
				utilfs.unlink(foodPhotoPath, function(err) {
						if(err) {
							console.log('删除失败');
						}
						else {
							console.log('删除成功');
						}
					});
				});
			}
			deferred.resolve(1);
		}, function(){
			deferred.reject('-0071');
		});
	}, function() {
		deferred.reject('-0070');
	});
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
};